package
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.system.Security;
	import flash.system.System;
	import flash.ui.Mouse;
	import flash.ui.MouseCursor;

	
	public class XINCopy extends Sprite
	{
		private var id:String;
		private var xWidth:int;
		private var xHeight:int;
		private var mouseOverFired:Boolean;
		private var button:Sprite;
		
		public function XINCopy()
		{
			mouseOverFired = false;

			Security.allowDomain("*");
			Security.allowInsecureDomain("*");
			
			var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
			id = flashvars.id;
			xWidth = flashvars.width
			xHeight = flashvars.height;
			xWidth = 9999; // if we draw the button with width and height from flashvar
			xHeight = 9999; // it doesn't work in ie7, seems the button scaled, so we just use a large size
			
			button = new Sprite();
			button.buttonMode = true;
			button.useHandCursor = true;
			button.graphics.beginFill( 0xCCFF00 );
			button.graphics.drawRect( 0, 0, Math.floor(xWidth), Math.floor(xHeight) );
			button.alpha = 0.0;
			this.stage.addChild( button );
			
			Mouse.cursor = MouseCursor.BUTTON;
			
			this.stage.addEventListener( MouseEvent.CLICK, 			doCopy );
			this.stage.addEventListener( MouseEvent.MOUSE_MOVE, 	stageMouseEvent );
			this.stage.addEventListener( Event.MOUSE_LEAVE, 		stageMouseEvent );
			this.stage.addEventListener( MouseEvent.MOUSE_UP, 		stageMouseEvent );
			this.stage.addEventListener( MouseEvent.MOUSE_DOWN, 	stageMouseEvent );
		}

		
		private function doCopy( event:Event ):void{
			trace( "mouse click" );
			var content:String = ExternalInterface.call( "XINCopyGetContent", id ).toString();
			System.setClipboard( content );
		}
		
		private function stageMouseEvent( event:Event ):void{
			if( event.type == "mouseMove" ){
				// Simulate MouseOver event
				if( mouseOverFired == false ){
					trace( "mouseOver" );
					ExternalInterface.call( "XINCopyEvent", id, "mouseOver" );
					mouseOverFired = true;
				}
			}else{
				trace( event.type );
				ExternalInterface.call( "XINCopyEvent", id, event.type );
			}
			
			if( event.type == "mouseLeave" ){
				// Simulate MouseOver event
				mouseOverFired = false;
			}
		}
	}
}